package cn.droidlover.xdroidmvp.mvp;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.ColorRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle2.components.support.RxFragment;
import java.util.List;
import butterknife.Unbinder;
import cn.droidlover.xdroidmvp.R;
import cn.droidlover.xdroidmvp.XDroidConf;
import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.kit.KnifeKit;
import cn.droidlover.xdroidmvp.util.EmptyUtil;
import cn.droidlover.xdroidmvp.util.ScreenUtils;
import cn.droidlover.xdroidmvp.view.widget.ColorDividerDecoration;
import cn.droidlover.xdroidmvp.view.NotRecordView;

/**
 * @author by DELL
 * @date on 2017/9/27
 * @describe 通用的列表刷新Fragment
 * 上拉刷新用的是 SmartRefreshLayout
 * 下拉加载用的是 BaseAdapter带的
 * 注意事项：
 * 刷新控件 id必须为：mRefreshLayout
 * RecyclerView id必须为：mRecyclerView
 * 当然也可以自己调整
 */
public abstract class RefreshFragment<P extends IPresent> extends RxFragment implements
        BaseQuickAdapter.RequestLoadMoreListener,IView<P>{
    /*** 每页请求数量 */
    public int PAGE_COUNT = 10;
    /*** 页码，默认从1开始 */
    protected int PageStart = 1;
    protected int mPage = 1;
    /*** 空布局类型 可以在这里设置默认值 */
    protected int emptyType = 1;
    /*** 是否启用空布局 */
    private boolean enableEmptyView = false;

    protected SmartRefreshLayout mRefreshLayout;
    protected RecyclerView mRecyclerView;
    private BaseQuickAdapter mAdapter;

    private VDelegate vDelegate;
    private P p;
    protected Activity context;
    private View rootView;
    protected LayoutInflater layoutInflater;
    private RxPermissions rxPermissions;
    private Unbinder unbinder;

    //Fragment的View加载完毕的标记
    private boolean isViewCreated;
    //Fragment对用户可见的标记
    private boolean isUIVisible;

    protected int screenWidth;

    //默认需要设置paddingTop高度为状态栏高度
    private boolean shouldPaddingTop = true;

    @Override
    public void onStart() {
        super.onStart();
        int statusBarHeight = ScreenUtils.getStatusBarHeight(context);
        //动态设置状态栏高度
        if (shouldPaddingTop) {
            rootView.setPadding(0, statusBarHeight, 0, 0);
        }
        if (useEventBus()) {
            BusProvider.getBus().register(this);
        }
    }

    protected void setShouldPaddingTop(boolean shouldPaddingTop) {
        this.shouldPaddingTop = shouldPaddingTop;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        layoutInflater = inflater;
        if (rootView == null && getLayoutId() > 0) {
            rootView = inflater.inflate(getLayoutId(), null);
            bindUI(rootView);
        } else {
            ViewGroup viewGroup = (ViewGroup) rootView.getParent();
            if (viewGroup != null) {
                viewGroup.removeView(rootView);
            }
        }

        getP();
        if (useEventBus()) {
            BusProvider.getBus().register(this);
        }
        bindEvent();
        screenWidth = ScreenUtils.getWindowWidth(context);

        initData(savedInstanceState);
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
        lazyLoad();
    }


    @Override
    public void bindUI(View rootView) {
        unbinder = KnifeKit.bind(this, rootView);
    }

    protected VDelegate getVDelegate() {
        if (vDelegate == null) {
            vDelegate = VDelegateBase.create(context);
        }
        return vDelegate;
    }

    protected P getP() {
        if (p == null) {
            p = newP();
        }
        if (p != null) {
            if (!p.hasV()) {
                p.attachV(this);
            }
        }
        return p;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof Activity) {
            this.context = (Activity) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        context = null;
    }

    @Override
    public boolean useEventBus() {
        return false;
    }

    @Override
    public P newP() {
        return null;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (useEventBus()) {
            BusProvider.getBus().unregister(this);
        }
        if (getP() != null) {
            getP().detachV();
        }
        getVDelegate().destroy();

        p = null;
        vDelegate = null;
        KnifeKit.unbind(unbinder);
        isViewCreated = false;
        isUIVisible = false;
    }

    protected RxPermissions getRxPermissions() {
        rxPermissions = new RxPermissions(getActivity());
        rxPermissions.setLogging(XDroidConf.DEV);
        return rxPermissions;
    }

    @Override
    public int getOptionsMenuId() {
        return 0;
    }

    @Override
    public void bindEvent() {

    }

    @Override
    public int getLayoutId() {
        return 0;
    }

    @Override
    public void initData(Bundle savedInstanceState) {

    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见
        if (isVisibleToUser) {
            isUIVisible = true;
            lazyLoad();
        } else {
            isUIVisible = false;
        }
    }

    private void lazyLoad() {
        //这里进行双重标记判断,是因为setUserVisibleHint会多次回调,并且会在onCreateView执行前回调,必须确保onCreateView加载完毕且页面可见,才加载数据
        if (isViewCreated && isUIVisible) {
            loadData();
            //数据加载完毕,恢复标记,防止重复加载
            isViewCreated = false;
            isUIVisible = false;
            //Log.i("xx","走了");
        }
    }

    /**
     * 设置刷新框架，需要时调用即可
     */
    protected void initRefreshLayout() {
        mRefreshLayout = getView().findViewById(R.id.mRefreshLayout);
        if (mRefreshLayout != null) {
            mRefreshLayout.setEnableRefresh(true);
            mRefreshLayout.setEnableLoadMore(false);
            mRefreshLayout.setEnableAutoLoadMore(false);
            mRefreshLayout.setDisableContentWhenLoading(true);
            mRefreshLayout.setDisableContentWhenRefresh(true);
            //单布局适用
            mRefreshLayout.setOnRefreshListener(refreshlayout -> RefreshFragment.this.onRefresh());
            //多条目布局使用此方法
            mRefreshLayout.setOnLoadMoreListener(refreshLayout -> RefreshFragment.this.onLoadMoreRequested());

        }
    }

    public void setPageCount(int pageCount) {
        PAGE_COUNT = pageCount;
    }

    public void setPageStart(int pageStart) {
        PageStart = pageStart;
    }

    /**
     * 开关刷新
     *
     * @param enableRefresh
     */
    public void setEnableRefresh(boolean enableRefresh) {
        if (mRefreshLayout != null)
            mRefreshLayout.setEnableRefresh(enableRefresh);
    }

    /**
     * 初始化列表控件
     */
    protected void initRecyclerView() {
        mRecyclerView = (RecyclerView) getView().findViewById(R.id.mRecyclerView);
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
    }

    /**
     * 设置分割线
     *
     * @param id
     */
    protected void addItemDecoration(@ColorRes int id) {
        if (mRecyclerView != null) {
            mRecyclerView.addItemDecoration(new ColorDividerDecoration(ContextCompat.getColor(getActivity(), id)));
        }
    }

    protected void addItemDecoration(@ColorRes int id, int dp) {
        if (mRecyclerView != null) {
            mRecyclerView.addItemDecoration(new ColorDividerDecoration(ContextCompat.getColor(getActivity(), id), ScreenUtils.dp2px(getActivity(), dp)));
        }
    }

    protected void addItemDecoration() {
        //设置默认分割线
        if (mRecyclerView != null) {
            mRecyclerView.addItemDecoration(new ColorDividerDecoration(Color.parseColor("#f4f4f4")));
        }
    }


    /**
     * 自动刷新
     */
    public void autoRefresh() {
        if (mRefreshLayout != null)
            mRefreshLayout.autoRefresh(0);
    }

    /**
     * 结束刷新
     */
    public void finishRefresh() {
        if (mRefreshLayout != null)
            mRefreshLayout.finishRefresh(0);
    }


    /***
     * 是否启用空布局
     * @param enableEmptyView
     */
    public void setEnableEmptyView(boolean enableEmptyView) {
        this.enableEmptyView = enableEmptyView;
    }

    public void setEnableEmptyView(boolean enableEmptyView, int emptyType) {
        this.enableEmptyView = enableEmptyView;
        this.emptyType = emptyType;
    }


    public void setLoadData(BaseQuickAdapter adapter, List<?> list) {
        setLoadData(adapter, list, emptyType);//emptyType 可以给一个默认值,作为统一设置
    }

    /**
     * 不分页的 设置数据
     *
     * @param adapter
     * @param list
     * @param emptyType
     */
    public void setLoadData(BaseQuickAdapter adapter, List<?> list, int emptyType) {
        this.mAdapter = adapter;
        this.emptyType = emptyType;
        adapter.setHeaderFooterEmpty(true, true);//是否显示头部和底部

        finishRefresh();
        adapter.setNewData(list);
        if (EmptyUtil.isEmpty(list)) {
            setEmptyView(adapter);
        }
    }


    public void setLoadMore(BaseQuickAdapter adapter, List<?> list) {
        setLoadMore(adapter, list, emptyType);
    }

    /**
     * 如果使用的是当前的 mRecyclerView
     *
     * @param adapter
     * @param list
     * @param emptyType
     */
    public void setLoadMore(BaseQuickAdapter adapter, List<?> list, int emptyType) {
        if (mRecyclerView != null) {
            setLoadMore(mRecyclerView, adapter, list, emptyType);
        }
    }


    /**
     * 结束刷新
     * 自动设置上拉更多
     *
     * @param adapter
     * @param list
     */
    public void setLoadMore(RecyclerView recyclerView, BaseQuickAdapter adapter, List<?> list, int emptyType) {
        this.mAdapter = adapter;
        this.emptyType = emptyType;
        adapter.setHeaderFooterEmpty(true, true);//是否显示头部和底部

        finishRefresh();//结束刷新
        if (mPage == PageStart) {
            adapter.setNewData(list);
            if (EmptyUtil.isEmpty(list)) {
                setEmptyView(adapter);
            }
        } else {
            if (list != null && !list.isEmpty()) {
                adapter.addData(list);
            }
        }

        handleLoadMore(recyclerView, adapter, list);
    }

    public void handleLoadMore(RecyclerView recyclerView, BaseQuickAdapter adapter, List<?> list) {
        if (list == null || list.size() < PAGE_COUNT) {
            adapter.loadMoreEnd();
        } else {
            adapter.setEnableLoadMore(true);
            adapter.setOnLoadMoreListener(this, recyclerView);
            adapter.loadMoreComplete();
        }
    }

    /**
     * 设置空状态
     * <p>
     * 根据项目情况 自由定制
     *
     * @param adapter
     */
    protected void setEmptyView(BaseQuickAdapter adapter) {

        if (enableEmptyView) {
            NotRecordView view = new NotRecordView(getContext());
            view.setType(emptyType);
            adapter.setEmptyView(view);
        }
    }

    /**
     * 结束刷新
     */
    @Override
    public void onRequestFinish() {
        finishRefresh();
    }

    /**
     * 如需上啦加載更多
     */
    public void onRefresh() {
        finishRefresh();
    }

    /**
     * 如需上拉更多 请重写该方法
     */
    @Override
    public void onLoadMoreRequested() {
        mRefreshLayout.finishLoadMore();

    }


    protected void loadData(){};


}
